import { getUserInfo } from '@/services/userApi';
import { logout } from '@/services/loginApi';
import { clearToken } from '@/utils/authInterceptor';
import { UserOutlined } from '@ant-design/icons';
import { useModel, history } from '@umijs/max';
import { Avatar, Dropdown, Modal, Space, Spin, message } from 'antd';
import { useEffect, useState } from 'react';

interface UserInfo {
  id?: number;
  name?: string;
  nickName?: string;
  className?: string;
  stuNo?: string;
  phone?: string;
  email?: string;
  role?: string;
  gender?: number;
  avatar?: string;
  createTime?: string;
  updateTime?: string;
}

const RightContent: React.FC = () => {
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const { initialState } = useModel('@@initialState');

  useEffect(() => {
    // 如果initialState中已有用户信息，则直接使用
    if (initialState?.userInfo) {
      setUserInfo(initialState.userInfo);
      setLoading(false);
      return;
    }

    // 否则重新获取用户信息
    const fetchUserInfo = async () => {
      try {
        setLoading(true);
        const response = await getUserInfo();
        if (response && response.code === 200 && response.data) {
          setUserInfo(response.data);
        } else {
          message.error('获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息出错:', error);
        message.error('获取用户信息出错');
      } finally {
        setLoading(false);
      }
    };

    fetchUserInfo();
  }, [initialState]);

  // 构建完整的头像URL
  const getAvatarUrl = (avatar?: string) => {
    if (!avatar) return undefined;
    return `http://www.gameback.cn/${avatar}~tplv-trmyndwfss-image.image`;
  };

  // 处理退出登录
  const handleLogout = () => {
    Modal.confirm({
      title: '注销登录',
      content: '确定要注销登录吗？',
      okText: '确定',
      cancelText: '取消',
      okButtonProps: {
        danger: true,
      },
      onOk: async () => {
        try {
          // 调用退出登录API
          const response = await logout();
          if (response && response.code === 200) {
            // 清除token
            clearToken();
            message.success(response.message || '已退出登录');
            history.replace('/login');
          } else {
            message.error(response?.message || '退出登录失败');
          }
        } catch (error) {
          console.error('退出登录出错:', error);
          // 即使API调用失败，也清除本地token并跳转到登录页
          clearToken();
          message.warning('退出登录过程中出现错误，已强制退出');
          history.replace('/login');
        }
      },
    });
  };

  const items = [
    {
      key: 'userInfo',
      label: (
        <div style={{ padding: '8px 0' }}>
          <div style={{ marginBottom: '4px' }}>用户名: {userInfo?.name || '未知'}</div>
          {userInfo?.className && <div style={{ marginBottom: '4px' }}>班级: {userInfo.className}</div>}
          {userInfo?.stuNo && <div style={{ marginBottom: '4px' }}>学号: {userInfo.stuNo}</div>}
          {userInfo?.role && <div style={{ marginBottom: '4px' }}>角色: {userInfo.role}</div>}
          {userInfo?.email && <div style={{ marginBottom: '4px' }}>邮箱: {userInfo.email}</div>}
        </div>
      ),
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      label: '退出登录',
      onClick: handleLogout,
    },
  ];

  if (loading) {
    return <Spin size="small" style={{ marginRight: 8 }} />;
  }

  return (
    <Dropdown menu={{ items }} placement="bottomRight">
      <Space style={{ cursor: 'pointer', padding: '0 12px' }}>
        <Avatar 
          size="small" 
          icon={<UserOutlined />} 
          src={getAvatarUrl(userInfo?.avatar)}
          alt={userInfo?.name || '用户头像'}
        />
        <span style={{ color: '#fff' }}>{userInfo?.nickName || userInfo?.name || '用户'}</span>
      </Space>
    </Dropdown>
  );
};

export default RightContent;